package com.hzdl.library.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hzdl.library.dao.LibraryBookDao;
import com.hzdl.library.dao.impl.LibraryBookDaoImpl;
import com.hzdl.library.domain.BookInfo;
import com.hzdl.library.domain.RecordPageBean;
import com.hzdl.library.service.LibraryBookService;
import com.hzdl.library.util.DateUtil;
import com.hzdl.library.util.JedisUtil;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.List;

//孙彬棋
public class LibraryBookServiceImpl implements LibraryBookService {

    LibraryBookDao libraryBookDao = new LibraryBookDaoImpl();
    Jedis jedis = JedisUtil.getJedis();

    @Override
    public void addBook(BookInfo bookInfo) {
        libraryBookDao.addBook(bookInfo);
    }

    @Override
    public void deleteBook(String bookId) {
        libraryBookDao.deleteBook(bookId);
    }

    @Override
    public void updateBook(BookInfo bookInfo) {
        libraryBookDao.updateBook(bookInfo);
    }

    @Override
    public RecordPageBean<BookInfo> findAllBook(String book_id, String rows, String currentPage, String searchBook) throws JsonProcessingException {
        RecordPageBean<BookInfo> pageBean = new RecordPageBean<>();
        Integer rowsInteger = Integer.parseInt(rows);
        pageBean.setRows(rowsInteger);
        Integer currentPageInteger = Integer.parseInt(currentPage);
        pageBean.setCurrentPage(currentPageInteger);
        if("null".equals(searchBook)){
            searchBook = "";
        }
        Integer totalCount = libraryBookDao.findCountByBid(book_id,searchBook);
        pageBean.setTotalCount(totalCount);
        Integer totalPage = (totalCount % rowsInteger) == 0 ? (totalCount / rowsInteger) : (totalCount / rowsInteger) + 1;
        pageBean.setTotalPage(totalPage);
        Integer index = (currentPageInteger - 1) * rowsInteger;
        List<BookInfo> list = libraryBookDao.findPageByBid(book_id,index,rowsInteger,searchBook);
        ObjectMapper objectMapper = new ObjectMapper();
        String list_str = objectMapper.writeValueAsString(list);
        jedis.set("list",list_str);
//        for (BookInfo bookInfo : list) {
//            jedis.lpush("list_bookInfo", objectMapper.writeValueAsString(bookInfo));
//        }
        pageBean.setList(list);
        return pageBean;
    }

    @Override
    public BookInfo findDetail(String book_id) {
        return libraryBookDao.findDetail(book_id);
    }

    @Test
    public void method(){
        System.out.println(jedis.get("list"));
//        System.out.println(jedis.lrange("list_bookInfo",0,-1));
    }
}


